package com.zjut.zs.review.action;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;

import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import com.zjut.an.config.manager.AnConfigManager;
import com.zjut.an.user.dao.AnUser;
import com.zjut.an.user.manager.AnUserManager;
import com.zjut.an.util.module.PageModule;
import com.zjut.an.util.system.Status;
import com.zjut.an.util.tools.DateUtil;
import com.zjut.an.util.tools.JSONUtilClass;
import com.zjut.zs.applyview.dao.ZsApplyView;
import com.zjut.zs.applyview.manager.ZsApplyViewManager;
import com.zjut.zs.excel.tools.ExcelUtils;
import com.zjut.zs.excel.tools.JsGridReportBase;
import com.zjut.zs.excel.tools.TableData;
import com.zjut.zs.review.dao.ZsReview;
import com.zjut.zs.review.manager.ZsReviewManager;
import com.zjut.zs.user.dao.ZsUser;
import com.zjut.zs.user.manager.ZsUserManager;

public class ZsReviewAction extends ActionSupport implements
ServletResponseAware, ServletRequestAware, ModelDriven<ZsReview>{

	private HttpServletRequest request;
	private HttpServletResponse response;
	private HttpSession session;
	
	private ZsReview obj;
	private Map<String , Object> dataMap;
	private int page = 1, limit = 10;
	private String order;
	private String sort;
	private String search;
	private String rowstr;
	
	@Resource(name = "ZsReviewManager")
	private ZsReviewManager manager;

	@Resource(name = "ZsUserManager")
	private ZsUserManager umanager;

	@Resource(name = "AnUserManager")
	private AnUserManager anusermanager;

	@Resource(name = "ZsApplyViewManager")
	private ZsApplyViewManager vmanager;

	@Resource(name = "AnConfigManager")
	private AnConfigManager anconfig;

	@Resource(name = "DateUtil")
	private DateUtil dateutil;
	
	public String zsReviewList() {
		try {
			if (session.getAttribute("admin")!=null||session.getAttribute("user")!=null) {//只有管理员才允许执行该操作，以免信息泄露
				request.setCharacterEncoding("UTF-8");
				dataMap = new HashMap<String, Object>();
				PageModule module = manager.getDataByInstance(page, limit, sort, order, obj);
				dataMap.put("rows", module.getObjects());
				dataMap.put("total", module.getTotal()); 
				obj = null; 
			}			
			return SUCCESS;
		} catch (Exception e) {
			e.printStackTrace();
			return ERROR;
		}		
	}
	
	@SuppressWarnings("unchecked")
	public String zsReviewDeletes() {
		try {
			String objumniJSON = rowstr;
			manager.deleteDatas(JSONUtilClass.getDTOList(objumniJSON, ZsReview.class));
			dataMap = new HashMap<String, Object>();
			dataMap.put("flag", "success");
			return SUCCESS;
		} catch (Exception e) {
			e.printStackTrace();
			return ERROR;
		}		
	}
	
	public String zsReviewAdd() {//重新生成专家评价表
		try {
			manager.deleteDatas(manager.getDatas());//清空已经有的
			
			int page = 3;
			if (null!=anconfig.getSingleConfigInfoByName("评分次数")) {
				page = Integer.parseInt(anconfig.getSingleConfigInfoByName("评分次数"));
			}
			//专业分组模式：取出报考专业，根据材料评审范围（是否是初审通过还是提交），依次将该报考专业的考生取出，，然后根据评分次数同时生成几份待评分表，放入待分配列表
			//然后取出该专业的专家，将待分配评分表和评审专家放入循环分配队列中进行分配，根据专业报考人数的不同和专家数目的不同，不同专业专家拿到的评分材料是不同的。
			String pfms = anconfig.getSingleConfigInfoByName("评分模式");
			if (null!=pfms && ("column1".equals(pfms)
					||"column2".equals(pfms)
					||"column3".equals(pfms)
					||"column4".equals(pfms)
					||"sColumn1".equals(pfms)
					||"sColumn2".equals(pfms)
					||"sColumn3".equals(pfms)
					||"sColumn4".equals(pfms))) {
				String column1 = anconfig.getSingleConfigInfoByName("报考专业");
				String[] column1s = column1.split(",");
				for(int k=0; k<column1s.length; k++) {
					List reviewlist = new ArrayList();//待分配列表
					List anuserlist = new ArrayList();//专家列表
					
					String column = column1s[k];
					ZsApplyView app = new ZsApplyView();
					
					if("column1".equals(pfms)) {
						app.setInZymc01(column);
					} else if ("column2".equals(pfms)) {
						app.setInZymc02(column);
					} else if ("column3".equals(pfms)) {
						app.setInZymc03(column);
					} else if ("column4".equals(pfms)) {
						app.setInZymc04(column);
					} else if ("sColumn1".equals(pfms)) {
						app.setScColumn1(column);
					} else if ("sColumn2".equals(pfms)) {
						app.setScColumn2(column);
					} else if ("sColumn3".equals(pfms)) {
						app.setScColumn3(column);
					} else if ("sColumn4".equals(pfms)) {
						app.setScColumn4(column);
					}
					
					if ("已经初审通过".equals(anconfig.getSingleConfigInfoByName("专家评价表范围"))) {
						app.setCheckStatus(Status.CHECKSTATUS_YES.getStatus());
					} else if ("已经提交".equals(anconfig.getSingleConfigInfoByName("专家评价表范围"))){
						app.setSendStatus(Status.SENDSTATUS_YES.getStatus());
						app.setCheckStatus(Status.CHECKSTATUS_NULL.getStatus());
					}	
					List applist = vmanager.getDataByInstance(1, 100000, "sendTime", "asc", app).getObjects(); //取出目标材料
					
					for (int i=0; i<applist.size(); i++) {
						app = (ZsApplyView)applist.get(i);
						
						for (int j=1; j<=page; j++) {
							obj = new ZsReview();
							obj.setUsId(app.getUsId());
							obj.setUsIdcard(app.getUsIdcard());
							obj.setUsName(app.getUsName());
							//同时保存几份
							manager.addData(obj);
							reviewlist.add(obj);//加到待分配列表
						}
					}
					AnUser user = new AnUser();
					user.setUsType(column);
					anuserlist = anusermanager.getDataByInstance(1, 100, null, null, user).getObjects();
					this.setReviewUser(reviewlist, anuserlist);//分配专家
				}
			} else if (null!=pfms && "专业分组评分".equals(pfms)) {
				String column1 = anconfig.getSingleConfigInfoByName("报考专业");
				String[] column1s = column1.split(",");
				for(int k=0; k<column1s.length; k++) {
					List reviewlist = new ArrayList();//待分配列表
					List anuserlist = new ArrayList();//专家列表
					
					String column = column1s[k];
					ZsApplyView app = new ZsApplyView();
					app.setInZymc01(column);
					if ("已经初审通过".equals(anconfig.getSingleConfigInfoByName("专家评价表范围"))) {
						app.setCheckStatus(Status.CHECKSTATUS_YES.getStatus());
					} else if ("已经提交".equals(anconfig.getSingleConfigInfoByName("专家评价表范围"))){
						app.setSendStatus(Status.SENDSTATUS_YES.getStatus());
						app.setCheckStatus(Status.CHECKSTATUS_NULL.getStatus());
					}	
					List applist = vmanager.getDataByInstance(1, 100000, "sendTime", "asc", app).getObjects(); //取出目标材料
					
					for (int i=0; i<applist.size(); i++) {
						app = (ZsApplyView)applist.get(i);
						
						for (int j=1; j<=page; j++) {
							obj = new ZsReview();
							obj.setUsId(app.getUsId());
							obj.setUsIdcard(app.getUsIdcard());
							obj.setUsName(app.getUsName());
							//同时保存几份
							manager.addData(obj);
							reviewlist.add(obj);//加到待分配列表
						}
					}
					AnUser user = new AnUser();
					user.setUsType(column);
					anuserlist = anusermanager.getDataByInstance(1, 100, null, null, user).getObjects();
					this.setReviewUser(reviewlist, anuserlist);//分配专家
				}
			} else if (null!=pfms && "标签分组评分".equals(pfms)) {
				String column1 = anconfig.getSingleConfigInfoByName("报考专业");
				String[] column1s = column1.split(",");
				for(int k=0; k<column1s.length; k++) {
					List reviewlist = new ArrayList();//待分配列表
					List anuserlist = new ArrayList();//专家列表
					
					String column = column1s[k];
					ZsApplyView app = new ZsApplyView();
					app.setScColumn2(column);
					if ("已经初审通过".equals(anconfig.getSingleConfigInfoByName("专家评价表范围"))) {
						app.setCheckStatus(Status.CHECKSTATUS_YES.getStatus());
					} else if ("已经提交".equals(anconfig.getSingleConfigInfoByName("专家评价表范围"))){
						app.setSendStatus(Status.SENDSTATUS_YES.getStatus());
						app.setCheckStatus(Status.CHECKSTATUS_NULL.getStatus());
					}	
					List applist = vmanager.getDataByInstance(1, 100000, "sendTime", "asc", app).getObjects(); //取出目标材料
					
					for (int i=0; i<applist.size(); i++) {
						app = (ZsApplyView)applist.get(i);
						
						for (int j=1; j<=page; j++) {
							obj = new ZsReview();
							obj.setUsId(app.getUsId());
							obj.setUsIdcard(app.getUsIdcard());
							obj.setUsName(app.getUsName());
							//同时保存几份
							manager.addData(obj);
							reviewlist.add(obj);//加到待分配列表
						}
					}
					AnUser user = new AnUser();
					user.setUsType(column);
					anuserlist = anusermanager.getDataByInstance(1, 100, null, null, user).getObjects();
					this.setReviewUser(reviewlist, anuserlist);//分配专家
				}
			} else if (null!=pfms && "人数分组评分".equals(pfms)) {
				//人数分组模式：人数分组，专家根据分组来形成组别，首先读取专家组一个专家需要评分的材料数目，然后读取组别的名称，再根据页码以及一页数目（一个专家评分数量）材料评审范围（是否是初审通过还是提交）将考生材料读取，然后根据评分次数同时生成几份待评分表，放入待分配列表
				//然后取出该组专家，将待分配评分表和评审专家放入循环分配队列中进行分配
				
				int team_fnum = Integer.parseInt(anconfig.getSingleConfigInfoByName("专家组材料数目"));
				String[] teams = anconfig.getSingleConfigInfoByName("专家组类型").split(",");
				for(int k=0; k<teams.length; k++) {
					List reviewlist = new ArrayList();//待分配列表
					List anuserlist = new ArrayList();//专家列表
					
					String team = teams[k];
					ZsApplyView app = new ZsApplyView();
					//app.setColumn1(column);
					if ("已经初审通过".equals(anconfig.getSingleConfigInfoByName("专家评价表范围"))) {
						app.setCheckStatus(Status.CHECKSTATUS_YES.getStatus());
					} else if ("已经提交".equals(anconfig.getSingleConfigInfoByName("专家评价表范围"))){
						app.setSendStatus(Status.SENDSTATUS_YES.getStatus());
						app.setCheckStatus(Status.CHECKSTATUS_NULL.getStatus());
					}	
					List applist = vmanager.getDataByInstance((k+1), team_fnum, "sendTime", "asc", app).getObjects(); //根据分组，一组需要的原始材料数目
					
					for (int i=0; i<applist.size(); i++) {//对材料进行复制
						app = (ZsApplyView)applist.get(i);
						
						for (int j=1; j<=page; j++) {
							obj = new ZsReview();
							obj.setUsId(app.getUsId());
							obj.setUsIdcard(app.getUsIdcard());
							obj.setUsName(app.getUsName());
							//同时保存几份
							manager.addData(obj);
							reviewlist.add(obj);//加到待分配列表
						}
					}
					AnUser user = new AnUser();
					user.setUsType(team);
					anuserlist = anusermanager.getDataByInstance(1, 100, null, null, user).getObjects();
					this.setReviewUser(reviewlist, anuserlist);//分配专家
				}
			} else {
				ZsApplyView app = new ZsApplyView();
				if ("已经初审通过".equals(anconfig.getSingleConfigInfoByName("专家评价表范围"))) {
					app.setCheckStatus(Status.CHECKSTATUS_YES.getStatus());
				} else if ("已经提交".equals(anconfig.getSingleConfigInfoByName("专家评价表范围"))){
					app.setSendStatus(Status.SENDSTATUS_YES.getStatus());
					app.setCheckStatus(Status.CHECKSTATUS_NULL.getStatus());
				}	
				List applist = vmanager.getDataByInstance(1, 100000, "sendTime", "asc", app).getObjects(); //取出所有目标材料
				for (int i=0; i<applist.size(); i++) {
					app = (ZsApplyView)applist.get(i);
					
					for (int j=1; j<=page; j++) {
						obj = new ZsReview();
						obj.setUsId(app.getUsId());
						obj.setUsIdcard(app.getUsIdcard());
						obj.setUsName(app.getUsName());
						//同时保存几份
						manager.addData(obj);
					}
				}
				List reviewlist = manager.getDatas();
				List anuserlist = anusermanager.getDatas();
				this.setReviewUser(reviewlist, anuserlist);//分配专家
			}
			
			dataMap = new HashMap<String, Object>();
			dataMap.put("flag", "success");
			return SUCCESS;
		} catch (Exception e) {
			e.printStackTrace();
			return ERROR;
		}
	}
	
	private void setReviewUser(List reviewlist, List anuserlist) {
		AnUser user;
		for (int i=0; i<reviewlist.size(); i++) {
			ZsReview obj = (ZsReview)reviewlist.get(i);
			
			int j = i;
			
			if (j>(anuserlist.size()-1)) {
				j=j%(anuserlist.size());//如果循环到最后一位专家，重新从0开始
			}
			System.out.println("@@@@@@@@@@@@@@ i:"+i+" j:"+j+" size:"+(anuserlist.size()-1));
			user = (AnUser)anuserlist.get(j);
			
			obj.setAnUsId(user.getUsId());
			obj.setAnAccount(user.getAccount());
			obj.setAnName(user.getName());
			manager.updateData(obj);
			System.out.println(obj.getReId()+"材料:"+obj.getUsName()+" 分配专家:"+ user.getName() +" ");
		}		
	}
	
	public void zsReviewExportExcel() throws Exception {
		try {
			request.setCharacterEncoding("UTF-8");
	        response.setContentType("application/msexcel;charset=utf-8");
	        
	        List list = manager.getDataByInstance(1, 100000, sort, order, obj).getObjects();
	        String title = "评分表";
	        //List columns = comanager.getDatasForExcel();
	        String[] hearders = new String[8];
            String[] fields = new String[8];
            //ZsCoName co = null;

            hearders[0]="id";
            hearders[1]="学生姓名";
            hearders[2]="身份证号";
            hearders[3]="专家账号";
            hearders[4]="专家姓名";
            hearders[5]="评分";
            hearders[6]="备注";
            hearders[7]="时间";

            fields[0]="reId";
            fields[1]="usName";
            fields[2]="usIdcard";
            fields[3]="anAccount";
            fields[4]="anName";
            fields[5]="num";
            fields[6]="remark";
            fields[7]="editTime";
                   
            TableData td = ExcelUtils.createTableData(list, ExcelUtils.createTableHeader(hearders),fields);
            
            JsGridReportBase report = new JsGridReportBase(request, response);
            report.exportToExcel(title, "admin", td, false);
		}catch(RuntimeException e) {
			e.printStackTrace();
		}
	}

	public String zsReviewDelete() {
		try {
			String objumniJSON = rowstr;
			//manager.deleteData((ZsReview)JSONUtilClass.getDTO(objumniJSON, ZsReview.class));
			manager.deleteData(manager.getData(Integer.parseInt(request.getParameter("hjId"))));
			dataMap = new HashMap<String, Object>();
			dataMap.put("flag", "success");
			return SUCCESS;
		} catch (Exception e) {
			e.printStackTrace();
			return ERROR;
		}		
	}
	
	public String zsReviewUpdate() {
		try {
			dataMap = new HashMap<String, Object>();
			String objumniJSON = rowstr;
			obj = (ZsReview)JSONUtilClass.getDTO(objumniJSON, ZsReview.class);
			ZsReview review = manager.getData(obj.getReId());
			review.setEditTime(dateutil.getCurrentDate5());
			review.setNum(obj.getNum());
			review.setRemark(obj.getRemark());
			//System.out.println("###############"+"是".equals(anconfig.getSingleConfigInfoByName("专家评审约束").trim()));
			if ("是".equals(anconfig.getSingleConfigInfoByName("专家评审约束").trim())) {
				AnUser user = anusermanager.getData(review.getAnUsId());
				
				String[] gz = user.getLawno().split(",");
				//System.out.println("###############  "+user.getLawno() + " 共"+ gz.length);
				for(int i=0;i<gz.length;i++) {					
					System.out.print(gz[i]+" ");
				}
				Map<String,String> gzmap = new HashMap();
				for(int i=0;i<gz.length;i++) {	
					//System.out.println("###############  "+gz[i].split(":")[0] + "  "+ gz[i].split(":")[1]);
					String fss = gz[i].split(":")[0];
					String fsnum = gz[i].split(":")[1];
					
					gzmap.put(gz[i].split(":")[0], gz[i].split(":")[1]);//把分数和分数限制数量放入map
				}
				String fsall = exit(obj.getNum(),gzmap);//取得该分数段的所有分数，如A+、A、A-
				if (null!=fsall) {//如果当前分数在打分分数范围内
					String[] fslist = fsall.split("、");
					int gzcount = Integer.valueOf(gzmap.get(fsall).toString());//取出该打分分数（如A）的限制数量
					ZsReview oldreview = new ZsReview();
					oldreview.setAnUsId(review.getAnUsId());
					int oldcount = 0;
					for (int i=0;i<fslist.length;i++) {
						oldreview.setNum(fslist[i]);
						oldcount += manager.getDataByInstance(1, 1000, null, null, oldreview).getTotal();//统计现有该专家已经打出的该分数（如A+、A-、A）数量总和
					}
					
					//System.out.println("############### "+oldreview.getUsId()+ " "+oldreview.getAnUsId()+ " "+oldreview.getNum()+" "+oldcount);
					//System.out.println("############### "+oldcount+ " "+gzcount+ " "+oldreview.getNum()+" "+(oldcount>=gzcount));
					if(oldcount>=gzcount) {//如果相同打分项（如A）已超过上限，不允许保存返回错误
						dataMap.put("flag", "gzerror");
					} else {//未超上限，则允许保存
						manager.updateData(review);
						dataMap.put("flag", "success");
					}
				} else {
					dataMap.put("flag", "gzerror");//不存在该打分项
				}
				
			} else {
				manager.updateData(review);
				dataMap.put("flag", "success");
			}			
			return SUCCESS;
		} catch (Exception e) {
			e.printStackTrace();
			return ERROR;
		}		
	}

	private String exit(String fs, Map<String,String> fsmap) {//判断map中是否有分数项存在，map可能一项为 A+、A、A-，如fs为A则判断为存在返回 A+、A、A-，否则返回null
		String fsall = null;
		for (String key : fsmap.keySet()) {
			if(key.contains(fs)) {
				fsall = key;
				return fsall;
			}
		}
		return fsall;
	}
	
	public String zsReview() {
		try {
			request.setCharacterEncoding("UTF-8");
			dataMap = new HashMap<String, Object>();
			Integer hjId = Integer.parseInt(request.getParameter("hjId"));
			obj = manager.getData(hjId);
			dataMap.put("rows", obj);
			obj = null;
			return SUCCESS;
		} catch (Exception e) {
			e.printStackTrace();
			return ERROR;
		}		
	}
	
	@Override
	public ZsReview getModel() {
		if (null == obj) {
			obj = new ZsReview();
		}
		return obj;
	}

	@Override
	public void setServletRequest(HttpServletRequest arg0) {
		request = arg0;
		session = request.getSession();
	}

	@Override
	public void setServletResponse(HttpServletResponse arg0) {
		response = arg0;
	}

	public HttpServletRequest getRequest() {
		return request;
	}

	public void setRequest(HttpServletRequest request) {
		this.request = request;
	}

	public HttpServletResponse getResponse() {
		return response;
	}

	public void setResponse(HttpServletResponse response) {
		this.response = response;
	}

	public HttpSession getSession() {
		return session;
	}

	public void setSession(HttpSession session) {
		this.session = session;
	}

	public ZsReview getAl() {
		return obj;
	}

	public void setAl(ZsReview obj) {
		this.obj = obj;
	}

	public Map<String, Object> getDataMap() {
		return dataMap;
	}

	public void setDataMap(Map<String, Object> dataMap) {
		this.dataMap = dataMap;
	}

	public String getRowstr() {
		return rowstr;
	}

	public void setRowstr(String rowstr) {
		this.rowstr = rowstr;
	}

	public ZsReviewManager getManager() {
		return manager;
	}

	public void setManager(ZsReviewManager manager) {
		this.manager = manager;
	}
	
	public int getPage() {
		return page;
	}

	public void setPage(int page) {
		this.page = page;
	}

	public int getLimit() {
		return limit;
	}

	public void setLimit(int limit) {
		this.limit = limit;
	}

	public String getOrder() {
		return order;
	}

	public void setOrder(String order) {
		this.order = order;
	}

	public String getSort() {
		return sort;
	}

	public void setSort(String sort) {
		this.sort = sort;
	}

	public String getSearch() {
		return search;
	}

	public void setSearch(String search) {
		this.search = search;
	}

}
